#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>

#define TASK_NUM 10

//预设一批任务

void sync_disk(){
  printf("sync_disk\n");
}

void sync_log(){
  printf("sync_log\n");
}

void net_send(){
  printf("net_send\n");
}

typedef void (*func_t)();
func_t other_task[TASK_NUM] = {NULL};


int LoadTask(func_t func){
  int i = 0;
  for(; i < TASK_NUM; i++){
    if(other_task[i] == NULL)
      break;
  }
  if(i == TASK_NUM)
    return -1;
  else 
    other_task[i] = func;
  return 0;
}

void InitTask(){
  int i = 0;
  for(; i < TASK_NUM; i++){
    other_task[i] = NULL;
  }
  LoadTask(sync_disk);
  LoadTask(net_send);
  LoadTask(sync_log);
}

void RunTask(){
  int i = 0;
  for(; i < TASK_NUM; i++){
    if(other_task[i] == NULL)
      continue;
    other_task[i]();
  }
}

int main(){
  pid_t id = fork();
  if(id == 0){
    //子进程
    int cnt = 50;
    while(cnt){
      printf("子进程, left %ds,pid: %d, ppid: %d\n",cnt--, getpid(), getppid());
      sleep(1);
    }
    if(1 == 1)
      exit(0);
    exit(111);
  }

  InitTask();
  //父进程
  
  while(1){
    int status = 0;
    pid_t ret_id = waitpid(id, &status, WNOHANG);
    if(ret_id < 0){
      printf("waitpid error\n");
      exit(-1);
    }
    else if(ret_id == 0){
      RunTask();
      sleep(1);
      continue;
    }
    else{
      if(WIFEXITED(status))
        printf("wait success, child exit code:%d\n", WEXITSTATUS(status));
      else 
        printf("wait success, child exit signal:%d\n", status & 0x7f);
      //printf("父进程, pid: %d, ppid: %d, ret_id: %d, child exit code: %d, signal: %d\n", getpid(), getppid(), ret_id, (status>>8)&0xff, status&0x7f);
      break;
    }
  }
  
 // sleep(5);

}
